package com.baike.service.impl;

import com.baike.entity.TbLesson;
import com.baike.mapper.TbLessonMapper;
import com.baike.service.ITbLessonService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2021-10-29
 */
@Service
public class TbLessonServiceImpl extends ServiceImpl<TbLessonMapper, TbLesson> implements ITbLessonService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TbLessonMapper lessonMapper;

    //合并购物车
    @Override
    public List<TbLesson> merageCartList(List<TbLesson> lessonListCookie, List<TbLesson> listCartFromRedis, String studentAccount) {
        //cookie 购物车
        for (TbLesson lesson : lessonListCookie) {
            boolean b = listCartFromRedis.contains(lesson);
            if (!b){
                listCartFromRedis.add(lesson);
            }
        }
        redisTemplate.boundHashOps("cartList").put(studentAccount,listCartFromRedis);
        return listCartFromRedis;
    }

    //
    @Override
    public List<TbLesson> addCart(List<TbLesson> cartList, Integer itemId) {
        //1.根据itemId 查询item商品
        TbLesson lesson = lessonMapper.selectById(itemId);
        //定义一个List集合,把用户需要的商品加入集合
        List<TbLesson> list = new ArrayList<>();
        list.add(lesson);
        return list;
    }

    @Override
    public void addCartListToRedis(List<TbLesson> cartList, String uname) {
        redisTemplate.boundHashOps("cartList").put(uname,cartList);
    }

    //封装方法,根据商家id查询购物车对象
    private TbLesson findCartBySellerId(List<TbLesson> cartList, Integer lessonId) {
        for (TbLesson lesson : cartList){
            if (Objects.equals(lesson.getLessonTeacherId(),lessonId)){
                return lesson;
            }
        }
        return null;
    }


    //获取购物车
    @Override
    public List<TbLesson> findListCartFromRedis(String uname) {
        //根据用户名获取redis购物车数据
        List<TbLesson> lessonList = (List<TbLesson>) redisTemplate.boundHashOps("cartList").get(uname);
        //如果数据为空
        if (lessonList == null){
            //new 一个 空容器
            lessonList = new ArrayList<>();
        }
        return lessonList;
    }
}
